package com.purchase.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.purchase.entity.OrderDetail;
import com.purchase.util.LogInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.purchase.mapper.OrderMapper;
import com.purchase.mapper.StoreActivityMapper;
import com.purchase.mapper.WxUserMapper;
import com.purchase.service.StatisticsService;
import com.purchase.util.DateUtil;
import com.purchase.util.RequestForm;
import com.purchase.util.ResponseForm;

import lombok.extern.slf4j.Slf4j;

import static java.util.stream.Collectors.groupingBy;

import java.math.BigDecimal;

@Service
@Slf4j
public class StatisticsServiceImpl implements StatisticsService {
	@Resource
	OrderMapper orderMapper;
	@Resource
	StoreActivityMapper saMapper;
	@Resource
	WxUserMapper wuMapper;

	@Override
	public ResponseForm getSalesAndPriceData(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if (param.getData() != null) {
			/* 今日: 总价 单数 商品 */
			Map paramMap = (Map) param.getData();
			paramMap.put("startTime", DateUtil.toDate(paramMap.get("startTime")));
			paramMap.put("endTime", DateUtil.toDate(paramMap.get("endTime")));
			LinkedHashMap resultMap = new LinkedHashMap<>();
			try {
				Map orderStatistics = orderMapper.getOrderStatistics(paramMap);
				resultMap.put("orderStatistics", orderStatistics);
			} catch (Exception e) {
				result.setStatus(false);
				result.setMessage("参数错误");
				log.error("参数错误");
				e.printStackTrace();
			}
			/* 按活动:总价 单数 商品件数 */
			try {
				/* 获取有数据的活动列表 */
				List<Map> activities = saMapper.getActivities(paramMap);
				if (activities != null) {
					for (Map activity : activities) {
						activity.put("startTime", paramMap.get("startTime"));
						activity.put("endTime", paramMap.get("endTime"));
						Map orderStatistics = orderMapper.getOrderStatistics(activity);
						activity.put("orderStatistics", orderStatistics);
					}
				}
				resultMap.put("activitiesOrderStatistics", activities);
			} catch (Exception e) {
				result.setStatus(false);
				result.setMessage("参数错误");
				log.error("参数错误");
				e.printStackTrace();
			}
			result.setData(resultMap);
		}
		return result;
	}

	@Override
	public ResponseForm getActivityOrderData(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			LinkedList<OrderDetail> orderDetails = orderMapper.getActivityOrderData(paramMap);
			LinkedList<Object> activityList = this.getGroupList(orderDetails);
			result.setData(activityList);
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("获取活动订单详情error", e);
		}
		return result;
	}

	/**
	 * 按 活动和订单 分组
	 *
	 * @param orderDetails
	 *            活动订单详情列表
	 * @return
	 */
	private LinkedList<Object> getGroupList(List<OrderDetail> orderDetails) {
		// 按 活动ID 分组
		LinkedList<Object> activityList = new LinkedList<>();
		Map<Integer, List<OrderDetail>> collectByActivity = orderDetails.parallelStream()
				.collect(groupingBy(OrderDetail::getActivityId));

		// 遍历 collectByActivity，以取到 first 里的活动名称活动ID 和订单列表
		collectByActivity.forEach((k, v) -> {
			Map<String, Object> mapByActivity = new HashMap<>();
			String activityName = v.get(0).getActivityName();
			mapByActivity.put("activityId", k);
			mapByActivity.put("activityName", activityName);

			// 按 订单ID 分组
			List<Map<String, Object>> orderList = new ArrayList<>();
			Map<String, List<OrderDetail>> collectByOrder = v.parallelStream()
					.collect(groupingBy(OrderDetail::getOrderId));

			// 遍历 collectByOrder，以取到 first 里的订单ID 和商品列表
			collectByOrder.forEach((k1, v1) -> {
				Map<String, Object> mapByOrder = new HashMap<>();
				mapByOrder.put("orderId", k1);
				mapByOrder.put("orderPrice", v1.get(0).getOrderPrice());
				mapByOrder.put("postage", v1.get(0).getPostage());
				mapByOrder.put("orderStatus", v1.get(0).getOrderStatus());
				mapByOrder.put("logisticStatus", v1.get(0).getLogisticStatus());
				mapByOrder.put("orderGoodsNum", v1.get(0).getOrderGoodsNum());
				mapByOrder.put("contacts", v1.get(0).getContacts());
				mapByOrder.put("phone", v1.get(0).getPhone());
				mapByOrder.put("address", v1.get(0).getAddress());
				mapByOrder.put("createTime", v1.get(0).getCreateTime());
				mapByOrder.put("orderList", v1);
				orderList.add(mapByOrder);
			});

			// 按时间倒序
			List<Map<String, Object>> sortedTimeList = orderList.parallelStream().sorted(Comparator
					.comparingLong((Map<String, Object> c) -> ((Date) (c.get("createTime"))).getTime()).reversed())
					.collect(Collectors.toList());

			// activityList 中嵌套放入 sortedTimeList
			mapByActivity.put("activityList", sortedTimeList);
			activityList.add(mapByActivity);
		});
		return activityList;
	}

//	@SuppressWarnings(value = { "rawtypes", "unused", "unchecked" })
//	@Override
//	public ResponseForm channelInfoStatistics(RequestForm param) {
//		ResponseForm result = new ResponseForm();
//		if (param.getData() != null) {
//			Map paramMap = (Map) param.getData();
//			paramMap.put("startTime", DateUtil.toDate(paramMap.get("startTime")));
//			paramMap.put("endTime", DateUtil.toDate(paramMap.get("endTime")));
//			// Date startTime = DateUtil.toDate(paramMap.get("startTime"));
//			// Date endTime = DateUtil.toDate(paramMap.get("endTime"));
//			// String channel = (String) paramMap.get("channel");
//			Map resultMap = new HashMap<>();
//			try {
//				/* 人数 */
//				List<Map> userList = wuMapper.quantityStatistics(paramMap);
//				/* 订单明细 */
//				List<Map> orderDetails = orderMapper.orderDetailStatistics(paramMap);
//				/* 百分比 */
//				BigDecimal percentum = new BigDecimal(0.15 + "");
//				/* 提成 */
//				BigDecimal profit = new BigDecimal(0);// 提成
//				BigDecimal totalFeeCount = new BigDecimal(0);// 总销售额
//				BigDecimal postageCount = new BigDecimal(0);// 运费
//				for (Map order : orderDetails) {
//					totalFeeCount = totalFeeCount.add(new BigDecimal(order.get("totalFee").toString()));
//					postageCount = postageCount.add(new BigDecimal(order.get("postage").toString()));
//				}
//				totalFeeCount = totalFeeCount.subtract(postageCount);// 总价-运费
//				profit = totalFeeCount.multiply(percentum).setScale(2, BigDecimal.ROUND_HALF_UP);// 提成=总价*百分比
//				resultMap.put("quantity", Long.valueOf(userList.size()));
//				resultMap.put("orderQuantity", Long.valueOf(orderDetails.size()));
//				resultMap.put("profit", profit);
//				resultMap.put("totalFeeCount", totalFeeCount);
//				result.setStatus(true);
//				result.setCode("200");
//				result.setData(resultMap);
//			} catch (Exception e) {
//				e.printStackTrace();
//				result.setStatus(false);
//				result.setCode("400");
//				result.setMessage("请求错误");
//				log.error("请求错误");
//			}
//		} else {
//			result.setCode("400");
//			result.setStatus(false);
//			result.setMessage("参数不为空或缺少必要参数");
//		}
//		return result;
//	}

	@SuppressWarnings(value = { "rawtypes", "unused", "unchecked" })
	@Override
	public ResponseForm channelInfoStatistics(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if (param.getData() != null) {
			Map paramMap = (Map) param.getData();
			paramMap.put("startTime", DateUtil.toDate(paramMap.get("startTime")));
			paramMap.put("endTime", DateUtil.toDate(paramMap.get("endTime")));
			String wxUid = (String) paramMap.get("wxUid");
			// Date startTime = DateUtil.toDate(paramMap.get("startTime"));
			// Date endTime = DateUtil.toDate(paramMap.get("endTime"));
			// String channel = (String) paramMap.get("channel");
			Map resultMap = new HashMap<>();
			try {
				/* 人数 */
				List<Map> userList = wuMapper.quantityStatistics(paramMap);
				/* 订单明细 */
				List<Map> orderDetails = orderMapper.orderDetailStatistics(paramMap);
				/* 百分比 */
				BigDecimal percentum = new BigDecimal(0.15 + "");
				/* 提成 */
				BigDecimal profit = new BigDecimal(0);// 提成
				BigDecimal totalFeeCount = new BigDecimal(0);// 总销售额
				BigDecimal postageCount = new BigDecimal(0);// 运费
				BigDecimal mineFeeCount = new BigDecimal(0);// 自己下单的总金额
				BigDecimal mineProfit = new BigDecimal(0);// 自己下单的提成=自己下单的总金额*百分比
				BigDecimal bFeeCount = new BigDecimal(0);// 子B下单的总金额
				BigDecimal bProfit = new BigDecimal(0);// 子B的提成=子B下单*百分比*百分比
				BigDecimal cFeeCount = new BigDecimal(0);// 子C下单的总金额
				BigDecimal cProfit = new BigDecimal(0);// 子C的提成=子C下单*百分比
				for (Map order : orderDetails) {
					totalFeeCount = totalFeeCount.add(new BigDecimal(order.get("totalFee").toString()));
					totalFeeCount=totalFeeCount.subtract(new BigDecimal(order.get("postage").toString()));//总金额去运费
//					postageCount = postageCount.add(new BigDecimal(order.get("postage").toString()));
					if (order.get("wxUid").toString().equals(wxUid)&&order.get("isChannel").equals(1)) {
						/* 自己 */
						mineFeeCount = mineFeeCount.add(new BigDecimal(order.get("totalFee").toString()));
						mineFeeCount = mineFeeCount.subtract(new BigDecimal(order.get("postage").toString()));// 自己下单的总金额(去运费)
					} else if (order.get("isChannel").equals(1)) {
						/* 子B */
						bFeeCount = bFeeCount.add(new BigDecimal(order.get("totalFee").toString()));
						bProfit = bProfit.subtract(new BigDecimal(order.get("postage").toString()));// 子B下单的总金额(去运费)
					} else if (order.get("isChannel").equals(0)) {
						/* 子C */
						cFeeCount = cFeeCount.add(new BigDecimal(order.get("totalFee").toString()));
						cProfit = cProfit.subtract(new BigDecimal(order.get("postage").toString()));// 子C下单的总金额(去运费)
					}
				}
				mineProfit=mineFeeCount.multiply(percentum).setScale(2, BigDecimal.ROUND_HALF_UP);
				bProfit=(bFeeCount.multiply(percentum)).multiply(percentum).setScale(2, BigDecimal.ROUND_HALF_UP);
				cProfit=cFeeCount.multiply(percentum).setScale(2, BigDecimal.ROUND_HALF_UP);
				profit=profit.add(mineProfit).add(bProfit).add(cProfit);
//				totalFeeCount = totalFeeCount.subtract(postageCount);// 总价-运费
//				profit = totalFeeCount.multiply(percentum).setScale(2, BigDecimal.ROUND_HALF_UP);// 提成=总价*百分比
				resultMap.put("quantity", Long.valueOf(userList.size()));
				resultMap.put("orderQuantity", Long.valueOf(orderDetails.size()));
				resultMap.put("profit", profit);
				resultMap.put("totalFeeCount", totalFeeCount);
				result.setStatus(true);
				result.setCode("200");
				result.setData(resultMap);
			} catch (Exception e) {
				e.printStackTrace();
				result.setStatus(false);
				result.setCode("400");
				result.setMessage("请求错误");
				log.error("请求错误");
			}
		} else {
			result.setCode("400");
			result.setStatus(false);
			result.setMessage("参数不为空或缺少必要参数");
		}
		return result;
	}
	
	@SuppressWarnings({ "unused", "rawtypes", "unchecked" })
	@Override
	public ResponseForm channelUserDetails(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if (param.getData() != null) {
			Map paramMap = (Map) param.getData();
			paramMap.put("startTime", DateUtil.toDate(paramMap.get("startTime")));
			paramMap.put("endTime", DateUtil.toDate(paramMap.get("endTime")));
			// Date startTime = DateUtil.toDate(paramMap.get("startTime"));
			// Date endTime = DateUtil.toDate(paramMap.get("endTime"));
			// String channel = (String) paramMap.get("channel");
			Map resultMap = new HashMap<>();
			try {
				/* 人数 */
				com.purchase.util.Page.parsePage(paramMap);
				Page<Object> pageHelper = PageHelper.startPage((int) paramMap.get("page"), (int) paramMap.get("size"));
				List<Map> userList = wuMapper.quantityStatistics(paramMap);
				result.setCode("200");
				result.setStatus(true);
				result.setData(userList);
				result.setTotal((int) pageHelper.getTotal());
			} catch (Exception e) {
				e.printStackTrace();
				result.setStatus(false);
				result.setCode("400");
				result.setMessage("请求错误");
				log.error("请求错误");
			}
		} else {
			result.setCode("400");
			result.setStatus(false);
			result.setMessage("参数不为空或缺少必要参数");
		}
		return result;
	}

	@Override
	public ResponseForm channelUserOrders(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if (param.getData() != null) {
			Map paramMap = (Map) param.getData();
			paramMap.put("startTime", DateUtil.toDate(paramMap.get("startTime")));
			paramMap.put("endTime", DateUtil.toDate(paramMap.get("endTime")));
			// Date startTime = DateUtil.toDate(paramMap.get("startTime"));
			// Date endTime = DateUtil.toDate(paramMap.get("endTime"));
			// String channel = (String) paramMap.get("channel");
			Map resultMap = new HashMap<>();
			try {
				/* 订单明细 */
				com.purchase.util.Page.parsePage(paramMap);
				Page<Object> pageHelper = PageHelper.startPage((int) paramMap.get("page"), (int) paramMap.get("size"));
				List<Map> orderDetails = orderMapper.orderDetailStatistics(paramMap);
				result.setCode("200");
				result.setStatus(true);
				result.setData(orderDetails);
				result.setTotal((int) pageHelper.getTotal());
			} catch (Exception e) {
				e.printStackTrace();
				result.setStatus(false);
				result.setCode("400");
				result.setMessage("请求错误");
				log.error("请求错误");
			}
		} else {
			result.setCode("400");
			result.setStatus(false);
			result.setMessage("参数不为空或缺少必要参数");
		}
		return result;
	}
	
	public static void main(String[] args) {
		Object a = 1;
		Object b = 0;
		System.out.println(b.equals(0));
	}
}
